package android.textIt.frontend.activity;

import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.textIt.R;
import android.textIt.backend.dao.*;
import android.textIt.backend.model.*;
import android.textIt.frontend.adapter.ContactListAdapter;
import android.textIt.frontend.adapter.GroupAdapter;
import android.textIt.util.TextItUtil;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

public class MainActivity extends TabActivity {
  private final static  String DEBUG_TAG = "TextIt Main";  

  private final static int TAB_CONTACTS = 0;
	private final static int TAB_GROUPS = 1;
	private final static int TAB_MESSAGES = 2;
	private final static int PHONE_TYPE_MOBILE = 2;
	private final static int ACTIVITY_NEWGROUP = 0;
	private final static int ACTIVITY_VIEWMESSAGES = 1;

  private static UserDao userDAO;
  private static GroupDao groupDAO;
  private static MessageDao messageDAO;
  public static User phoneOwner;
  
  private ListView lvContacts;
  private ListView lvGroups;
  private ListView lvMessages;

  
	public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
    userDAO = new UserDao(this);
    groupDAO = new GroupDao(this);
    messageDAO = new MessageDao(this);

		lvContacts = (ListView)findViewById(R.id.listContacts);
		lvGroups = (ListView)findViewById(R.id.listGroups);
		lvMessages = (ListView)findViewById(R.id.listMessages);

    TabHost mTabHost = getTabHost();    
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts", getResources().getDrawable(R.drawable.contact)).setContent(R.id.tabContacts));
    mTabHost.addTab(mTabHost.newTabSpec("groups").setIndicator("Groups", getResources().getDrawable(R.drawable.group)).setContent(R.id.tabGroups));
    mTabHost.addTab(mTabHost.newTabSpec("messages").setIndicator("Messages", getResources().getDrawable(R.drawable.message)).setContent(R.id.tabMessages));    
    mTabHost.setCurrentTab(0);
    bindListView(TAB_CONTACTS);	   
    bindListView(TAB_GROUPS);	   
    bindListView(TAB_MESSAGES);	 
    bindOnClickHandlers();
    registerForContextMenu(findViewById(R.id.listGroups));
    registerForContextMenu(findViewById(R.id.listContacts));
    phoneOwner = userDAO.getUserbyID(1);

	}
	
	private void bindOnClickHandlers() {
		lvContacts.setOnItemClickListener(new OnItemClickListener() {
		    @Override
		    public void onItemClick(AdapterView<?> parent, View v, int i, long l) {  
		    	  TextView tvID = (TextView) v.findViewById(R.id.TxtContactIGroupId);
		        Log.v(DEBUG_TAG, tvID.getText().toString());
		        String groupId = tvID.getText().toString();
		        viewMessages(groupId, TextItUtil.TO_INDIVIDUAL);
		    }                
		});
		lvGroups.setOnItemClickListener(new OnItemClickListener() {
		    @Override
		    public void onItemClick(AdapterView<?> parent, View v, int i, long l) {  
		    	  TextView tvID = (TextView) v.findViewById(R.id.TxtGroupId);
		        Log.v(DEBUG_TAG, tvID.getText().toString());
		        String groupId = tvID.getText().toString();
		        viewMessages(groupId, TextItUtil.TO_GROUP);
		    }                
		});
		lvMessages.setOnItemClickListener(new OnItemClickListener() {
		    @Override
		    public void onItemClick(AdapterView<?> parent, View v, int i, long l) {  
		        Log.v(DEBUG_TAG, "onItemClick fired!");
		        //TextView tvID = (TextView) v.findViewById(R.id.TxtGroupId);
		        //Log.v(DEBUG_TAG, tvID.getText().toString());
		    }                
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.groups_menu, menu);
    return true;
	}
	
	//  only add the menu to add group when current tab is groups
	@Override
	public boolean onPrepareOptionsMenu (Menu menu){
		if (getTabHost().getCurrentTab() == TAB_GROUPS){
			return true;
		}
		else return false;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		if (v.getId() == R.id.listGroups){
			inflater.inflate(R.menu.groups_context_menu, menu);
		}
		if (v.getId() == R.id.listContacts){
			inflater.inflate(R.menu.contacts_context_menu, menu);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.add_group:
	        newGroup();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    TextView idTextView; 
	  int item_id;
	  switch (item.getItemId()) {
		  case R.id.edit_contact:
		  	idTextView = (TextView)info.targetView.findViewById(R.id.TxtContactId);
			  item_id = Integer.parseInt((String) idTextView.getText());
	  		editContact(item_id);
				return true;
		  case R.id.edit_group:
		  	idTextView = (TextView)info.targetView.findViewById(R.id.TxtGroupId);
			  item_id = Integer.parseInt((String) idTextView.getText());
	  		editGroup(item_id);
				return true;
		  case R.id.delete_group:
		  	idTextView = (TextView)info.targetView.findViewById(R.id.TxtGroupId);
			  item_id = Integer.parseInt((String) idTextView.getText());
	  		deleteGroup(item_id);
		    return true;
		  default:
		    return super.onContextItemSelected(item);
	  }
	}

	private void editContact(int id){
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.dlg_edit_contact);
    dialog.setTitle("Edit Contact");                
    final User user = userDAO.getUserbyID(id);
    
    final TextView txtName = (TextView) dialog.findViewById(R.id.TxtContactEditName);
    txtName.setText(user.getName());    
  
    Button btnSave = (Button)dialog.findViewById(R.id.btnSaveName);
    btnSave.setOnClickListener(
      new Button.OnClickListener(){
          @Override
          public void onClick(View arg0) {
	              String name = txtName.getText().toString().trim(); 
	              
	              if (name.length()==0){
	              	new AlertDialog.Builder(MainActivity.this)
	                  .setTitle("Error")
	                  .setMessage("Please enter a name")
	                  .setNeutralButton("Ok", new DialogInterface.OnClickListener()
	                  {
	                    public void onClick(DialogInterface dlg, int sumthin)
	                    {
	                     
	                    }
	                  }).show();
	              return;        	
	              }           
	              user.setName(name);
	              userDAO.updateUser(user);
	              bindListView(getTabHost().getCurrentTab());
	              dialog.dismiss();
	          }
	      }
	   );	
    
    Button btnCancel=(Button)dialog.findViewById(R.id.btnCancelName);
    btnCancel.setOnClickListener(
	      new Button.OnClickListener(){
	    	  public void onClick(View arg0) {
	    		  dialog.cancel();
	        }
	    }
	 );	
    dialog.show();
    return;

	}
	
	private void editGroup(int id){
		Intent intent = new Intent();
    intent.setAction("Group.Detail");
    intent.putExtra( "id", Integer.toString(id));
  	startActivityForResult(intent, ACTIVITY_NEWGROUP);
  	return; 
	}
	
	private void deleteGroup(final int id){
		new AlertDialog.Builder(MainActivity.this)
		.setTitle("Confirm delete")
		.setMessage("Are you sure you want to delete this group?")
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				// Set the group as "temporary" so it doesn't show up on the list
		    public void onClick(DialogInterface dialog, int whichButton) {
		    	Group g = groupDAO.getGroupById(id);
		    	g.setIsTemporary(true);
		    	groupDAO.updateGroup(g);
		    	bindListView(getTabHost().getCurrentTab());
		  }
		})
		
		.setNegativeButton("No", new DialogInterface.OnClickListener() { // handler for no button
		      public void onClick(DialogInterface dialog, int whichButton) {
		
		      }
		  })
		.show();  // show all of this
		return; 
	}
	
	private void newGroup(){
		Intent intent = new Intent();
    intent.setAction("Group.Detail");
    intent.putExtra( "id", "0"); // use id of 0 to denote a new group
  	startActivityForResult(intent, ACTIVITY_NEWGROUP);
  	return; 
	}
	
	private void viewMessages(String groupId, int to){
		Intent intent = new Intent();
    intent.setAction("ViewMessages");
    intent.putExtra( "id", groupId); 
    intent.putExtra("to", to);
  	startActivityForResult(intent, ACTIVITY_VIEWMESSAGES);
  	return; 
	}
	
	private void bindListView(int tabId) {

			switch (tabId){
	    	case TAB_CONTACTS:
					ContactListAdapter cadapter = new ContactListAdapter(this, getContacts());
	        lvContacts.setAdapter(cadapter);
	        break;
	    	case TAB_GROUPS:
	    		GroupAdapter gadapter = new GroupAdapter(this, groupDAO.getPermanentGroups());
	        lvGroups.setAdapter(gadapter);    		
	    		break;
	    	case TAB_MESSAGES:
	    		//ListMessageAdapter lmadapter = new ListMessageAdapter(this, getTestMsgs());
	        //lvMessages.setAdapter(lmadapter);    		
	    		break;
	    }
	}

	private List<User> getContacts(){
			  
    try{

    	String[] projection = new String[] {
    			Data._ID, Data.DISPLAY_NAME, Phone.NUMBER			
    	};
    	
    	String where = Phone.TYPE + "=?" + " AND " +
    								Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
    	
    	String[] args = new String[] {String.valueOf(PHONE_TYPE_MOBILE)};
    
		  Cursor cursor = managedQuery(Data.CONTENT_URI, projection, where, args, Data.DISPLAY_NAME);
		 
	    if (cursor.moveToFirst()) {
   
        do {
          String phone = cursor.getString(cursor.getColumnIndex(Phone.DATA)).replaceAll("-", "");
  			  Log.v(DEBUG_TAG, "Got mobile phone number: " + phone);
  			  User user = new User();
  			  user.setName(cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME)));
  			  phone = phone.replaceAll("-", "");
  			  user.setPhone(Long.parseLong(phone));
  			  user.setIsTextItUser(0);
  			  userDAO.createUser(user);
  			  Log.v(DEBUG_TAG, "Got contact: " + user.getName() + 
      				" (" + Boolean.valueOf(user.isTextItUser()) +  ")");
      	
        } while (cursor.moveToNext());

    }
		 
    	cursor.close();
    	userDAO.updateContacts();
    	return TextItUtil.getMyContacts(MainActivity.this);
	  }
	    catch(Exception e){
	    	e.printStackTrace();
	    	return null;
	    }
	}


	private List<List<Message>> getTestMsgs(){
		List<List<Message>> superList = new ArrayList<List<Message>>();
		List<Message> list = new ArrayList<Message>();
		
		User u = userDAO.getUserbyID(2);
		User me = this.phoneOwner;
		list = messageDAO.getAllMessagesWithUser(u);
		if (list.size() < 2){
			Message m = new Message();
			Status s = new Status(1, "unread");
			m.setContent("hi");
			m.setSender(me);
			m.setReceiver(new Group (u.getiGroup()));
			m.setStatus(s);
			m.setReference_id(-1);
			messageDAO.createMessage(m);
			list.add(m);
			m = new Message();
			m.setContent("whats up");
			m.setSender(u);
			m.setReceiver(new Group (u.getiGroup()));
			m.setStatus(s);
			m.setReference_id(-1);
			messageDAO.createMessage(m);
			list.add(m);
		}
		superList.add(list);
		return superList;
	}

	@Override
  protected void onActivityResult(int requestCode, int resultCode,  Intent extras) {
    bindListView(TAB_GROUPS);	   
    bindListView(TAB_MESSAGES);	 

		switch(resultCode) {
			case Activity.RESULT_OK:
			case Activity.RESULT_CANCELED:
		}
	}	

}
